<template>
    <view class="device">
        <nav-bar></nav-bar>
        <view class="t_container">
            <!-- 	<view class="m-d" @click="$u.throttle(goList, 1000)" v-if="deviceList.length > 1">
				<text>所有仪器({{ deviceList.length }})</text>
				<text class="iconfont icon-youjiantou"></text>
			</view> -->
        </view>
        <view class="m_container">
            <view class="device_card" @click="$u.throttle(goDetails, 1000)">
                <!-- <view class="o_t">
					<text class="iconfont icon-a-ziyuan2" @click.stop="$u.throttle(goAdd, 1000)"></text>
				</view> -->
                <image :src=" ble.state == 0 ? img_2 : img_1 " class="device_mould" />
                <view class="s_d" v-if="!deviceList.length">
                    <view class="none">
                        未绑定仪器
                    </view>
                    <image @click.stop="$u.throttle(goAdd, 1000)"
                        src="http://oss.antaimedical.com/images/static/2024/06/6667e538eb14d0f049f44d056RtuRmgvPy5z2811d137cf52fe4d234dc466f46fa7de.png"
                        class="add" />
                </view>
                <view class="s_c" v-else>
                    <view class="d_name">
                        <view class="name" :style=" { color: ble.state === 0 ? '#333333' : '#CCCCCC' } ">
                            {{ ble.state === 0 ? ble.defaultInfo.name : defaultDev.bluetoothName }}
                        </view>
                        <u-image v-if="ble.state === 0" width="32rpx" height="32rpx" :showMenuByLongpress=" false "
                            src="http://oss.antaimedical.com/images/static/2024/07/66947d80eb14d0f049f44d556IGDqrK8xfZj335a584166aa26382d031e06222381c1.png"
                            :lazy-load=" true "></u-image>
                        <u-image v-else-if="ble.state === -1" width="32rpx" height="32rpx" :showMenuByLongpress=" false "
                            src="http://oss.antaimedical.com/images/static/2024/07/66947da0eb14d0f049f44d56N7Y0g57kb00R765831b67598dc25ba4a3728cd31b371.png"
                            :lazy-load=" true "></u-image>
                    </view>
                    <view class="d_i" v-if="ble.state === 0">
                        <text class="battery" v-if="ble.defaultInfo.battery">{{ ble.defaultInfo.battery }}%</text>
                        <u-loading-icon v-else size="14" :show=" true "></u-loading-icon>
                        <u-image width="44rpx" height="26rpx" :showMenuByLongpress=" false "
                            :src=" myGetBatteryIcon(ble.defaultInfo.battery) " :showLoading=" false " :showError=" false "
                            :lazy-load=" true "></u-image>
                        <text class="line"></text>
                        <text v-if="ble.defaultInfo.version">v{{ ble.defaultInfo.version }}</text>
                        <u-loading-icon v-else size="14" :show=" true "></u-loading-icon>
                        <text class="line"></text>
                        <text class="iconfont icon-lanya"></text>
                    </view>
                    <image v-else-if="ble.state !== 0 && defaultDev.bluetoothName !== ble.BleConnectedName"
                        @click.stop="$u.throttle(checkBleStatus, 2000)"
                        src="http://oss.antaimedical.com/images/static/2024/06/66680e5feb14d0f049f44d06n2i6YfGXBwVA8bd2a70c9e500c4dc43722120973ea93.png"
                        class="connect" />
                    <view class="connecting"
                        v-else-if="ble.state === -2 && defaultDev.bluetoothName === ble.BleConnectedName">
                        <text class="l-t">连接中</text>
                        <u-loading-icon size="18"></u-loading-icon>
                    </view>
                    <view class="connecting"
                        v-else-if="ble.state === -3 && defaultDev.bluetoothName === ble.BleConnectedName">
                        <text class="l-t">连接中</text>
                        <u-loading-icon size="18"></u-loading-icon>
                    </view>
                </view>
            </view>
            <view class="c-l">
                <view class="cell" v-for="(item, index) in options" :key=" index " @click="navigate(item.path)">
                    <text class="text">{{ item.text }}</text>
                    <text class="iconfont icon-arrow_rigth"></text>
                </view>
            </view>
            <!-- <view class="c-d">
				<view class="cell">
					<text class="text">如何使用</text>
					<text class="iconfont icon-arrow_rigth"></text>
				</view>
			</view> -->
        </view>
        <u-overlay :show=" showUpdate ">
            <view class="warp">
                <view class="pop_main">
                    <view class="content">
                        仪器固件状态异常,避免影响使用,请升级成功后使用
                    </view>
                    <view class="handle">
                        <view class="cancel" @click="showUpdate = false">
                            取消
                        </view>
                        <view class="confirm" @click=" goUpgrade ">
                            立即升级
                        </view>
                    </view>
                </view>
            </view>
        </u-overlay>
        <!-- <tab-bar :current="3"></tab-bar> -->
    </view>
</template>

<script>
import {
    getDeviceByUser
} from '@/api/index.js'
import {
    mapState
} from 'vuex'
import {
    hex2int,
    hexToString,
    getBatteryIcon,
} from '@/utils/utils.js'
const BLE = require('@/utils/ble.js');
export default {
    data () {
        return {
            paddingHeight: uni.getStorageSync('navbarHeight'),
            userId: uni.getStorageSync('userId'),
            img_1: 'http://oss.antaimedical.com/images/static/2024/08/66b47bdbe4b09217821c0fa97zzIw6raL2Bxc2f498c39041f05b1284c3871aab3e21.png',
            img_2: 'http://oss.antaimedical.com/images/static/2024/08/66b47bc1e4b000d2c606b524bblrMJK2gq935a3581f5f3a72a294dcfd449f2b1e19c.png',
            options: [
                // {
                // 	text: '仪器说明书', 
                // 	path: ''
                // },
                // {
                // 	text: '仪器使用记录',
                // 	path: ''
                // },
                {
                    text: '软件更新',
                    path: '/pagesA/device/update/index'
                },
                // {
                // 	text: '电子保修卡',
                // 	path: ''
                // }
            ],
            deviceList: [],
            defaultDev: undefined, // 默认仪器
            showUpdate: false,
            upgradeInfo: undefined
        }
    },
    computed: {
        ...mapState({
            ble: state => state.ble, // 实时蓝牙全局状态
            userInfo: state => state.userInfo
        })
    },
    onLoad () {
        this.fetchDeviceData()
        uni.$on('refreshDevice', () => {
            this.fetchDeviceData()
        })
    },
    onShow () {
        uni.$once('upgradeMsg', this.upgradeMsg)
    },
    onHide () {
        uni.$off('upgradeMsg', this.upgradeMsg)
    },
    onPullDownRefresh () {
        this.fetchDeviceData()
        setTimeout(() => {
            uni.stopPullDownRefresh()
        }, 1200)
    },
    methods: {
        // 连接默认仪器
        connect () {
            if (uni.$u.os() == 'android') { // 安卓系统直接连接
                console.log(this.defaultDev.deviceMac);
                this.$store.commit('setDefaultInfo', {
                    type: 1,
                    data: {
                        mac: this.defaultDev.deviceMac,
                        name: this.defaultDev.bluetoothName
                    }
                })
                BLE.common.createBLEConnectionFn(this.defaultDev.deviceMac, this.defaultDev)
            } else { // 苹果系统需要搜索uuid仪器id
                BLE.common.myStartBluetoothDevicesDiscovery(10000, this.defaultDev)
            }
            this.$store.commit('setBleConnectedName', this.defaultDev.bluetoothName)
        },
        // 获取已绑定仪器信息
        async fetchDeviceData (info) {
            uni.showLoading({
                title: '加载中...'
            })
            let params = {
                userId: this.userId,
                urlencoded: true
            }
            try {
                const res = await getDeviceByUser(params)
                if (res.code == 200) {
                    this.deviceList = res.data
                    this.defaultDev = this.deviceList.find(item => {
                        return item.isDefault == 1
                    })
                }
            } catch (e) {
                //TODO handle the exception
            }
            uni.hideLoading()
        },
        checkBleStatus () {
            let that = this
            if (this.ble.isOpenBleAdapter) {
                wx.getBluetoothAdapterState({
                    success: res => {
                        if (!res.available) {
                            uni.showModal({
                                title: '提示',
                                content: '检测到手机蓝牙未打开,请前往手机[设置]-[蓝牙]打开蓝牙功能以扫描附近仪器',
                                showCancel: false,
                                confirmColor: '#545DDE'
                            })
                        } else {
                            that.connect()
                        }
                    },
                    fail: err => {
                        uni.showModal({
                            title: '提示',
                            content: '请检查蓝牙功能是否正常',
                            showCancel: false
                        })
                    }
                })
            } else {
                wx.closeBluetoothAdapter()
                wx.openBluetoothAdapter({
                    success (BleObj) {
                        that.$store.commit('changeIsOpenBleAdapter', true)
                        that.connect()
                    },
                    fail (err) {
                        console.log('openBluetoothAdapter', err)
                        if (err.errCode == 10001) {
                            that.$store.commit('changeIsOpenBleAdapter', true)
                            uni.showModal({
                                title: '提示',
                                content: '检测到手机蓝牙未打开,请前往手机[设置]-[蓝牙]打开蓝牙功能以扫描附近仪器',
                                showCancel: false,
                                confirmColor: '#545DDE'
                            })
                        }
                        if (err.errMsg == 'openBluetoothAdapter:fail auth deny') {
                            uni.showModal({
                                title: '提示',
                                content: '请先授权蓝牙权限',
                                confirmColor: '#545DDE',
                                success (modal_res) {
                                    if (modal_res.confirm) {
                                        wx.openSetting({
                                            success: (authData) => {
                                                if (authData.authSetting[
                                                    'scope.bluetooth']) {
                                                    that.checkBleStatus()
                                                } else { // 未授权
                                                    uni.showModal({
                                                        title: '提示',
                                                        content: '授权失败,您将无法使用蓝牙相关服务',
                                                        confirmColor: '#545DDE',
                                                        showCancel: false,
                                                        success (modal) {
                                                            if (modal
                                                                .confirm) {
                                                                wx.closeBluetoothAdapter()
                                                                that.$store.commit(
                                                                    'changeIsOpenBleAdapter',
                                                                    false)
                                                            }
                                                        }
                                                    })

                                                }
                                            }
                                        })
                                    } else {
                                        uni.showModal({
                                            title: '提示',
                                            content: '授权失败,您将无法使用蓝牙相关服务',
                                            confirmColor: '#545DDE',
                                            showCancel: false,
                                            success (modal) {
                                                if (modal.confirm) {
                                                    wx.closeBluetoothAdapter()
                                                    that.$store.commit(
                                                        'changeIsOpenBleAdapter',
                                                        false)
                                                }
                                            }
                                        })
                                    }
                                }
                            })
                        } else {
                            uni.showModal({
                                title: '提示',
                                content: '连接失败，请重启仪器再次连接。',
                                confirmColor: '#545DDE',
                                showCancel: false,
                                success (modal) {
                                    if (modal.confirm) {
                                        wx.closeBluetoothAdapter()
                                        that.$store.commit(
                                            'changeIsOpenBleAdapter',
                                            false)
                                    }
                                }
                            })
                        }
                    }
                })
            }
        },
        upgradeMsg (res) {
            console.log('upgradeMsgCheck', res)
            let result = res.substr(-6, 2)
            if (result == '04' || result == '02') {
                let length = hex2int(res.substr(-14, 8))
                let index = length / 128
                // 接收数据体数据起始字节为十四
                let s_byte = 16
                // 获取固件版本号前面的硬件数据长度累加  因前面硬件版本数据长度不固定 无法直接读取
                let p_len = hex2int(res.substr(s_byte, 2))
                s_byte += (p_len * 2) + 2
                let vsLen = hex2int(res.substr(s_byte, 2))
                s_byte += 2
                let version = hexToString(res.substr(s_byte,
                    vsLen * 2))
                console.log(version)
                this.upgradeInfo = {
                    index,
                    version
                }
                // 监测设备发送需要升级通知
                this.showUpdate = true
            }
        },
        goDetails () {
            if (!this.deviceList.length) return
            uni.navigateTo({
                url: `/pagesA/device/details/index?details=${JSON.stringify(this.defaultDev)}&type=default`
            })
            // if (this.ble.state === 0) {
            // 	let deviceInfo = this.deviceList.find(item => {
            // 		return item.bluetoothName == this.ble.defaultInfo.name
            // 	})
            // 	uni.navigateTo({
            // 		url: `/pagesA/device/details/index?details=${JSON.stringify(deviceInfo)}&type=default`
            // 	})
            // } else {

            // }
        },
        // 跳转升级
        goUpgrade () {
            this.showUpdate = false
            let dev = JSON.stringify(this.defaultDev)
            uni.navigateTo({
                url: `/pagesA/device/update/index?index=${this.upgradeInfo.index}&version=${this.upgradeInfo.version}&deviceInfo=${dev}`
            })
        },
        // 跳转
        navigate (url) {
            if (!this.defaultDev) {
                uni.showToast({
						title: '当前暂未绑定仪器',
						icon: 'none'
					})
				} else {
					uni.navigateTo({
						url: `${url}?deviceInfo=${JSON.stringify(this.defaultDev)}`
					})
				}
			},
			myGetBatteryIcon(data) {
				return getBatteryIcon(data)
			},
			goAdd() {
				uni.navigateTo({
					url: '/pagesA/device/search/index?type=default'
				})
			},
			goList() {
				uni.navigateTo({
					url: '/pagesA/device/list/index'
				})
			}
		}
	}
</script>
<style lang="scss">
page {
    background-color: #F6F7FD !important;
    min-height: 100%;
}
</style>
<style lang="scss" scoped>
.t_container {
    width: 100%;
    height: 556rpx;
    background-image: url('http://oss.antaimedical.com/images/static/2024/08/66ac9a14e4b000d2c606b51bKtP0NbqctY5U39a744c1b547badc117d392dbc405dfb.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
}

.m_container {
    width: 100%;
    border-radius: 48rpx 48rpx 0rpx 0rpx;
    background-color: #F6F7FD;
    margin-top: -264rpx;
    padding: 96rpx 48rpx 48rpx;

    .device_card {
        width: 100%;
        padding: 108rpx 32rpx 48rpx;
        border-radius: 16rpx;
        background-color: #fff;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;

        .o_t {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: flex-end;

            .icon-a-ziyuan2 {
                font-size: 56rpx;
                color: #666666;
            }
        }

        .device_mould {
            width: 120rpx;
            height: 320rpx;
        }

        .s_d {
            margin-top: 46rpx;
            display: flex;
            flex-direction: column;
            align-items: center;

            .none {
                font-size: 36rpx;
                color: #333333;
            }

            .add {
                width: 132rpx;
                height: 132rpx;
                margin-top: 48rpx;
            }
        }

        .s_c {
            width: 100%;
            margin-top: 48rpx;
            display: flex;
            flex-direction: column;
            align-items: center;

            .d_name {
                display: flex;
                align-items: center;

                .name {
                    font-weight: 500;
                    font-size: 36rpx;
                    padding-right: 8rpx;
                }
            }

            .d_i {
                margin-top: 32rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 24rpx;
                color: #666;

                .battery {
                    padding-right: 12rpx;
                }

                .line {
                    width: 1rpx;
                    height: 22rpx;
                    background-color: rgba(#000, .1);
                    margin: 0 16rpx;
                }

                .icon-lanya {
                    color: #666666;
                    font-size: 34rpx;
                }
            }

            .connect {
                width: 100%;
                height: 88rpx;
                margin-top: 90rpx;
            }

            .connecting {
                margin: 54rpx 0 80rpx;
                display: flex;
                align-items: center;

                .l-t {
                    font-size: 32rpx;
                    color: #333333;
                    padding-right: 10rpx;
                }
            }
        }
    }

    .c-l,
    .c-d {
        margin-top: 32rpx;

        .cell {
            width: 100%;
            height: 118rpx;
            padding: 0 54rpx 0 48rpx;
            background: #FFFFFF;
            border-radius: 16rpx;
            margin-bottom: 16rpx;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .text {
                font-size: 32rpx;
                color: #666666;
            }

            .icon-arrow_rigth {
                font-size: 34rpx;
					color: rgba(#666666, .5);
				}
			}
		}
	}
</style>